import { defineStore } from "pinia";
import defaultConfig from "@/config";
import { sign } from '@/api/bgame';
import { receiveGift } from '@/api/gift';

export const useUserStore = defineStore("user", {
  state: () => ({
    userInfo: {
      user: { id: 0 },
      organ: { id: 0 },
      accessToken: "",
      organEmployee: { id: 0 },
      employee: { id: 0 }
    } as ApiData.Session,
    user: null as ApiData.User | null,
    organ: null as ApiData.Organ | null,
    userId: 0 as number,
    organId: 0 as number,
    channel: "WX",
    accessToken: "" as string,
    // 登录页的免登录存储几天，默认7天
    loginDay: 7,
    isHasSubsidy: 0,//是否有百万补贴
    checkIsHasCW: false,
  }),
  actions: {
    //写入用户信息
    setUserInfo(info: ApiData.Session, updateIsCheck = true) {
      this.userInfo = info;
      this.user = info.user;
      this.organ = info.organ;
      this.userId = info.user.id;
      this.organId = info.organ.id;
      this.accessToken = info.accessToken || 'DEV';
      //用户信息写入缓存
      uni.setStorageSync(defaultConfig.loginKey, JSON.stringify(info));
      if (updateIsCheck) {
        this.checkIsHasCW = true;
      }
    },
    //修改用户信息
    setUser(user: ApiData.User) {
      this.user = user;
      if (this.userInfo) this.userInfo.user = user;
      this.user = user;
      //用户信息写入缓存
      uni.setStorageSync(defaultConfig.loginKey, JSON.stringify(this.userInfo));
    },
    //修改企业信息
    setOrgan(organ: ApiData.Organ) {
      this.organ = organ;
      if (this.userInfo) this.userInfo.organ = organ;
      this.organ = organ;
      //用户信息写入缓存
      uni.setStorageSync(defaultConfig.loginKey, JSON.stringify(this.userInfo));
    },
    //获取登录信息
    getUserInfo(): ApiData.Session | null {
      let localUser = uni.getStorageSync(defaultConfig.loginKey);
      if (localUser && !this.userId) {
        this.setUserInfo(JSON.parse(localUser) as ApiData.Session);
        return this.userInfo;
      }
      return null;

    },
    setAccessToken(token: string) {
      this.accessToken = token;
    },
    setIsHasSubsidy(val: number) {
      this.isHasSubsidy = val;
    },
    //清空信息
    clearUserInfo(isLogin = true) {
      this.userInfo = {
        user: { id: 0 },
        organ: { id: 0 },
        accessToken: "",
        organEmployee: { id: 0 },
        employee: { id: 0 }
      };
      this.user = null;
      this.organ = null;
      this.userId = 0;
      this.organId = 0;
      this.accessToken = "";
      uni.removeStorageSync(defaultConfig.loginKey);
      uni.removeStorageSync(defaultConfig.storageHasSubsidyKey);
      isLogin && uni.reLaunch({ url: '/pages/login/bind-mobile' });
    },
    //退出登录
    loginOut() {
      this.clearUserInfo();
    },
    async getSign() {
      console.log('user_getSign', uni.getStorageSync('user_id'));
      const user_id = uni.getStorageSync('user_id');
      if (user_id > 0) {
        return
      }
      const { code } = await uni.login();

      const res: any = await sign({
        code: code,
      });
      // 登陆成功
      if (1 == res.result) {
        // 保存token
        uni.setStorageSync('adopt_state', res.data.data.adopt_state);
        uni.setStorageSync('user_id', res.data.data.uid);
        uni.setStorageSync('user_avatarUrl', res.data.data.avatar);
        uni.setStorageSync('user_nickName', res.data.data.username);
        uni.setStorageSync('phone', res.data.data.mobile);

        const giftId = uni.getStorageSync('giftId');
        const share_user_id = uni.getStorageSync('share_user_id') || 0;
        if (giftId && Number(giftId) > 0 && share_user_id && Number(share_user_id) > 0) {
          uni.showModal({
            title: '提示',
            content: `ID:${share_user_id}送你1张沐浴露礼包卡`,
            confirmText: '查收',
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {

                receiveGift({
                  receive_id: res.data.data.uid,
                  gift_receive_id: giftId,
                });
                uni.setStorageSync('giftId', '');
              }
            },
          });
        }
      }
    },
  }
});

export function useUserStoreHook() {
  return useUserStore();
}